<script lang="ts">
    import { Modal } from "@skeletonlabs/skeleton-svelte";
    import { X } from "lucide-svelte";
    import type { Store as ToastStore } from "@zag-js/toast";
    import { getContext } from "svelte";
    import { gen_invite } from "$lib/api/board/board_member";
    import { boardStore } from "$lib/stores/board.svelte";
    import { userStore } from "$lib/stores/user.svelte";
    import { request } from "$lib/utils/request";
    import dayjs from "dayjs";
    import { writeText } from "@tauri-apps/plugin-clipboard-manager";

    const toast: ToastStore = getContext("toast");

    interface ModalProps {
        onClose: () => void;
    }
    let props: ModalProps = $props();

    let ttlHour = $state(1);
    let inviteCode = $state("");

    async function genInvite() {
        const res = await request(
            gen_invite({
                session_id: userStore.userSession,
                board_id: boardStore.curBoardId,
                ttl_hour: ttlHour,
            }),
        );
        toast.create({
            title: "成功",
            description: "生成邀请码成功!",
            type: "success",
        });
        inviteCode = res.invite_code;
    }

    async function copyAndClose() {
        const codePart = `${userStore.userInfo?.basic_info.display_name ?? ""}邀请您加入频道 ${boardStore.curWebBoard?.boardInfo?.basic_info.board_name ?? ""} 。您的邀请码是 ${inviteCode} 。有效时间截止到 ${dayjs().add(ttlHour, "hours").format("YYYY-MM-DD HH:mm")} 。`;
        const downloadPart = `如果您还没有下载第E梯队的应用，您可以从https://gitcode.com/eteam/desktop/releases下载最新版本。`;
        await writeText(codePart + "\n" + downloadPart);
        toast.create({
            title: "成功",
            description: "复制成功!",
            type: "success",
        });
        props.onClose();
    }
</script>

<Modal
    open={true}
    triggerBase="btn preset-tonal"
    contentBase="card bg-surface-200-800 p-4 space-y-4 shadow-xl w-[500px]"
    backdropClasses="backdrop-blur-xs"
    backdropBase="backdrop-none"
    onOpenChange={(ev) => {
        if (!ev.open) {
            props.onClose();
        }
    }}
>
    {#snippet content()}
        <header class="flex justify-between">
            <h4 class="h4">邀请频道成员</h4>
            <button
                type="button"
                class="btn preset-ghost-primary-500"
                onclick={() => {
                    props.onClose();
                }}
            >
                <X />
            </button>
        </header>

        {#if inviteCode == ""}
            <label
                class="label border-[1px] relative p-2 border-surface-300-700"
            >
                <span
                    class="label-text absolute top-[-10px] left-[10px] bg-surface-200-800 pl-2 pr-2"
                    >有效时长</span
                >
                <select
                    class="select rounded-none bg-surface-100-900"
                    bind:value={ttlHour}
                >
                    <option value={1}>1小时</option>
                    <option value={3}>3小时</option>
                    <option value={24}>1天</option>
                    <option value={24 * 3}>3天</option>
                    <option value={24 * 7}>1周</option>
                    <option value={24 * 14}>2周</option>
                    <option value={24 * 30}>一月</option>
                </select>
            </label>
        {:else}
            <p class="break-all">
                {userStore.userInfo?.basic_info.display_name ??
                    ""}邀请您加入频道 {boardStore.curWebBoard?.boardInfo
                    ?.basic_info.board_name ?? ""} 。您的邀请码是 {inviteCode}
                。有效时间截止到 {dayjs()
                    .add(ttlHour, "hours")
                    .format("YYYY-MM-DD HH:mm")} 。
            </p>
            <p class="break-all">
                如果您还没有下载eteam应用，您可以从https://gitcode.com/eteam/desktop/releases下载最新版本。
            </p>
        {/if}

        <footer class="flex justify-end gap-4">
            {#if inviteCode == ""}
                <button
                    type="button"
                    class="btn preset-tonal"
                    onclick={() => {
                        props.onClose();
                    }}>取消</button
                >
            {/if}
            <button
                type="button"
                class="btn preset-filled-primary-900-100"
                onclick={() => {
                    if (inviteCode == "") {
                        genInvite();
                    } else {
                        copyAndClose();
                    }
                }}>{inviteCode == "" ? "生成" : "复制并关闭"}</button
            >
        </footer>
    {/snippet}
</Modal>
